package service

import (
	"dsc-server/domain/dto"
	"dsc-server/pkg/model"
	"fmt"
	"strconv"
	"strings"

	"gorm.io/gorm"
)

// TokenService 处理Token相关的服务
type TokenService struct {
	DB *gorm.DB
}

// NewTokenService 创建TokenService实例
func NewTokenService(db *gorm.DB) *TokenService {
	return &TokenService{DB: db}
}

// Auth 授权Token访问API分组
func (s *TokenService) Auth(tokenID uint, groupIDs string) dto.Result {
	// 开始事务
	tx := s.DB.Begin()

	// 删除原有授权
	if err := tx.Model(&model.ApiAuth{}).Where("token_id = ?", tokenID).Update("is_deleted", 1).Error; err != nil {
		tx.Rollback()
		return dto.FailureMessage(nil, fmt.Sprintf("删除原有授权失败: %v", err))
	}

	// 添加新授权
	if groupIDs != "" {
		groupIDList := strings.Split(groupIDs, ",")
		for _, groupIDStr := range groupIDList {
			groupID, err := strconv.ParseUint(groupIDStr, 10, 32)
			if err != nil {
				tx.Rollback()
				return dto.FailureMessage(nil, fmt.Sprintf("分组ID格式错误: %v", err))
			}

			auth := &model.ApiAuth{
				TokenID: tokenID,
				GroupID: int(groupID),
			}

			// 设置基础字段
			auth.BaseModel.ID = 0 // 确保是新记录

			if err := tx.Create(auth).Error; err != nil {
				tx.Rollback()
				return dto.FailureMessage(nil, fmt.Sprintf("添加授权失败: %v", err))
			}
		}
	}

	// 提交事务
	if err := tx.Commit().Error; err != nil {
		return dto.FailureMessage(nil, fmt.Sprintf("提交事务失败: %v", err))
	}

	// 清除缓存
	// TODO: 实现缓存清除逻辑

	return dto.SuccessMessage(nil, "授权成功")
}

// GetAuthGroups 获取Token授权的API分组ID列表
func (s *TokenService) GetAuthGroups(tokenID uint) ([]int, error) {
	var auths []model.ApiAuth
	result := s.DB.Model(&model.ApiAuth{}).
		Select("group_id").
		Where("token_id = ? AND is_deleted = 0", tokenID).
		Find(&auths)

	if result.Error != nil {
		return nil, result.Error
	}

	var groupIDs []int
	for _, auth := range auths {
		groupIDs = append(groupIDs, auth.GroupID)
	}

	// 缓存逻辑
	// TODO: 实现缓存逻辑

	return groupIDs, nil
}

// GetToken 根据Token字符串获取Token信息
func (s *TokenService) GetToken(tokenStr string) (*model.Token, error) {
	var token model.Token
	result := s.DB.Where("token = ? AND is_deleted = 0", tokenStr).First(&token)

	// 缓存逻辑
	// TODO: 实现缓存逻辑

	return &token, result.Error
}

// Insert 添加Token
func (s *TokenService) Insert(token *model.Token) dto.Result {
	if err := s.DB.Create(token).Error; err != nil {
		return dto.FailureMessage(nil, fmt.Sprintf("添加失败: %v", err))
	}

	return dto.SuccessMessage(nil, "添加成功")
}

// DeleteById 删除Token
func (s *TokenService) DeleteById(tokenID uint) dto.Result {
	// 开始事务
	tx := s.DB.Begin()

	// 删除Token
	if err := tx.Model(&model.Token{}).Where("id = ?", tokenID).Update("is_deleted", 1).Error; err != nil {
		tx.Rollback()
		return dto.FailureMessage(nil, fmt.Sprintf("删除Token失败: %v", err))
	}

	// 删除Token相关的授权
	if err := tx.Model(&model.ApiAuth{}).Where("token_id = ?", tokenID).Update("is_deleted", 1).Error; err != nil {
		tx.Rollback()
		return dto.FailureMessage(nil, fmt.Sprintf("删除Token授权失败: %v", err))
	}

	// 提交事务
	if err := tx.Commit().Error; err != nil {
		return dto.FailureMessage(nil, fmt.Sprintf("提交事务失败: %v", err))
	}

	// 清除缓存
	// TODO: 实现缓存清除逻辑

	return dto.SuccessMessage(nil, "删除成功")
}
